package com.eastfair.projectcore.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.eastfair.cache.redissonlock.RedisLock;
import com.eastfair.core.base.R;
import com.eastfair.projectcore.apollo.ApolloConfigBean;
import com.eastfair.security.constant.ValueConstant;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.stream.Collectors;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;

/**
 * <p>
 * 图形验证码
 * </p>
 *
 * @author ligang
 * @date 2021-07-22
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/common")
@Api(value = "common", tags = "公共方法类")
public class CommonController {

    @Value("${desensitizer.enabled}")
    private Boolean desensitizerEnabled;

    @Value("${com.eastfair.sensitivity_privateKey}")
    private String sensitivityPrivateKey;

    @Autowired
    ValueConstant valueConstant;


    @Value("${ef.dev-ip}")
    private String devIp;



    @Value("${AB.PUZZLE_136101}")
    private String PUZZLE_136101;

    @Autowired
    ApolloConfigBean apolloConfigBean;


    /**
     * 铭感信息开关
     *
     * @throws Exception
     */
    @GetMapping("/desensitizer")
    public R<Map<String, Object>> desensitizer() {
        List<String> list = new ArrayList<>();
        List<String> idCarFilesList = valueConstant.getIdCarFiles();
        List<String> mobileFilesList = valueConstant.getMobileFiles();
        List<String> emailFiles = valueConstant.getEmailFiles();
        if (CollectionUtil.isNotEmpty(idCarFilesList)) {
            list.addAll(idCarFilesList);
        }
        if (CollectionUtil.isNotEmpty(mobileFilesList)) {
            list.addAll(mobileFilesList);
        }
        if (CollectionUtil.isNotEmpty(emailFiles)) {
            list.addAll(emailFiles);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("enabled", desensitizerEnabled);
        result.put("filesList", list);
        return R.success(result);
    }

    /**
     * 数据脱敏：私钥
     *
     * @throws Exception
     */
    @GetMapping("/getSensitivityPrivateKey")
    public R<String> sensitivityPrivateKey() {
        return R.success(sensitivityPrivateKey);
    }


    @Autowired
    private WebApplicationContext applicationContext;

    @GetMapping("/getAllUrl")
    public List getAllUrl() {
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        // 获取url与类和方法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();

        List<Map<String, String>> list = new ArrayList<>();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) {
            Map<String, String> map1 = new HashMap<String, String>();
            RequestMappingInfo info = m.getKey();
            HandlerMethod method = m.getValue();
            //获取当前方法所在类名
            Class<?> bean = method.getBeanType();
            //使用反射获取当前类注解内容
            Api api = bean.getAnnotation(Api.class);
            RequestMapping requestMapping = bean.getAnnotation(RequestMapping.class);
            String[] value = requestMapping.value();
            map1.put("parent", value[0]);
            //获取方法上注解以及注解值
            ApiOperation methodAnnotation = method.getMethodAnnotation(ApiOperation.class);
            String privilegeName = methodAnnotation.value();
            PatternsRequestCondition p = info.getPatternsCondition();
            for (String url : p.getPatterns()) {
                map1.put("url", url);
            }
            map1.put("className", method.getMethod().getDeclaringClass().getName()); // 类名
            map1.put("method", method.getMethod().getName()); // 方法名
            RequestMethodsRequestCondition methodsCondition = info.getMethodsCondition();
            for (RequestMethod requestMethod : methodsCondition.getMethods()) {
                map1.put("type", requestMethod.toString());
            }
            if (map1.get("className").indexOf("com.eastfair") > -1) {
                list.add(map1);
            }
        }

        return list;
    }


    @PostMapping("/post1")
    @RedisLock(value = "blade:EnterpriseUserClient:lock:createExhibitorUser", param = "#resourceId")
    public String getAllUrl2(@RequestParam("resourceId") Long resourceId) {
        System.out.println(resourceId);
        try {
            Thread.sleep(3 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "1";
    }


    /**
     * 2、生成图片二进制流
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @throws Exception
     */
    @GetMapping("/fileOfStrem")
    public void defaultKaptcha(String filePath, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws Exception {
        // 构造URL
        URL url = new URL(filePath);
        // 打开连接
        URLConnection con = url.openConnection();
        //设置请求超时为20s
        con.setConnectTimeout(20 * 1000);
        //jdk 1.7 新特性自动关闭

        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
//        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();

        try (InputStream in = con.getInputStream()) {
            //创建缓冲区
            byte[] buff = new byte[1024];
            int n;
            // 开始读取
            while ((n = in.read(buff)) >= 0) {
//                out.write(buff, 0, n);
                responseOutputStream.write(buff, 0, n);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        responseOutputStream.flush();
        responseOutputStream.close();
    }


    @GetMapping("/test")
    public String getConfigByApollo(String namesapce, String key, String defaultValue) {
//        Config config = ConfigService.getConfig(namesapce);
//        String s = config.getProperty(key, defaultValue);
//        Config config = ConfigService.getConfig("JAVA.ab_config_version");
//        Set<String> propertyNames = config.getPropertyNames();
//        ObjectMapper mapper = new ObjectMapper();
//        for (String string : propertyNames) {
//            try {
//                String property = config.getProperty(string, "");
//                System.out.println(property);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }


        Config config2 =apolloConfigBean.getAbConfigVersion();
        Set<String> propertyNames2 = config2.getPropertyNames();
        for (String string : propertyNames2) {
            try {
                String property = config2.getProperty(string, "");
                System.out.println(property);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return "322222";
    }

    @GetMapping("/test2")
    public String test2() {
        log.info("PUZZLE_136101 is {}",PUZZLE_136101);
        return devIp;
    }
}
